﻿using Autofac;
using Microsoft.AspNetCore.Http;
using Shared.Contracts;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Shared.AutofacHelper
{
    public static class AutofacContainerBuilder
    {
        /// <summary>
        /// 查找bin文件夹下的所有DLL,进行注册
        /// </summary>
        /// <returns></returns>
        private static IEnumerable<Assembly> GetAssemblies()
        {
            List<Assembly> assemblies = new List<Assembly>();
            try
            {
                string[] files = Directory.GetFiles(AppContext.BaseDirectory, "*.dll");//得到文件
                foreach (string file in files)//循环文件
                {
                    try
                    {
                        //防止非 .net DLL 加载引发异常
                        //目前没有找到好方法进行判断是否是.net程序集,姑且先用try进行处理

                        //因为添加 7z.DLL 的使用所以此处出问题 
                        var assembly = Assembly.LoadFrom(file);
                        assemblies.Add(assembly);
                    }
                    catch (Exception ex)
                    { }
                }
            }
            catch (Exception ex)
            { }
            return assemblies;
        }
        /// <summary>
        /// Autofac 注册
        /// </summary>
        /// <param name="mvcControllerAssembly">
        /// 包含当前MVC执行的代码的程序集,
        /// 通过 Assembly.GetExecutingAssembly() 获取
        /// </param>
        public static void RegisterAssembly(this ContainerBuilder containerBuilder)
        {
            Type baseType = typeof(IDependency);
            Assembly[] assemblies = GetAssemblies().ToArray();

            containerBuilder.RegisterAssemblyTypes(assemblies)
                 .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface)
                 //.EnableInterfaceInterceptors() //启用接口的拦截器[AOP]
                 //.InterceptedBy(typeof(MethodInterceptor)) //拦截类型为MethodInterceptor[AOP]
                 .AsImplementedInterfaces()
                 .InstancePerLifetimeScope();//InstancePerLifetimeScope 保证生命周期基于请求
        }
    }
}
